﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Web.Mail;
using System.Net.Mail;
using System.IO;
using System.Web.UI;
using System.Net.Mime;
using System.Text;
using System.Configuration;

namespace WebProveedores.utilidades
{
    public static class envio_correo
    {
        public static string Configuracion(string destinatario, string asunto, string contenido, String idUsuario)
        {
            //MailMessage _message = new MailMessage();
            //SmtpClient mailClient = new SmtpClient("10.30.1.24", 25);
            string result;
            String cuerpo =  "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
            cuerpo += "<html xmlns=" + (char)34 + "http://www.w3.org/1999/xhtml" + (char)34 + "><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
            cuerpo += "    <style type=" + (char)34 + "text/css" + (char)34 + ">" +
                         "p.MsoNormal " +
	                      "  {margin-bottom:.0001pt;  " +
	                      "  font-size:12.0pt;  " +
	                      "  font-family:" + (char)34 + "Times New Roman" + (char)34 + "," + (char)34 + "serif" + (char)34 +
            "          margin-left: 0cm; " +
            "          margin-right: 0cm; " +
            "          margin-top: 0cm; " +
            "      } " +
            "      .style1 " +
            "      { " +
            "         text-align: center; " +
            "      } " +
            "      .style2 " +
            "      { " +
            "          width: 161px; " +
            "          font-family: Arial, Helvetica, sans-serif; " +
            "          font-size: x-large; " +
            "          color: #AEAEB0; " +
            "      } </style>";
			cuerpo += "</head><body>"+
                        "<table style=" + (char)34 + "width: 56%" + (char)34 + ">" + 
                        "  <tr> <td colspan=" + (char)34 + "2" + (char)34 + " class=" + (char)34 + "style1" + (char)34 + ">PORTAL PROVEEDORES<br />" +
                        "  GRUPO MILPO Y GRUPO VOTORANTIM <hr style=" + (char)34 + "color:blue;" + (char)34 + "/></td></tr> " +
                        " <tr> <td class=" + (char)34 + "style2" + (char)34 + " rowspan=" + (char)34 + "3" + (char)34 + ">" +
                        " <strong>&nbsp;  &nbsp;  Votorantim</strong></td>" +
                        " <td> Estimado Usuario: Su contraseña para consultar el Portal de Proveedores WEB <br />" +
                        " Votorantim fue modificado para :  " + contenido + " " +" <br /> " +
                        " ID USUARIO:  " + idUsuario + " " +"  <hr style=" + (char)34 + "color:blue;" + (char)34 + "/> " +
                        " </td> </tr> " +                    
                        " <tr> <td> &nbsp;Prezado Usuário: Sua senha para consultar o Portal Fornecedor WEB  " +
                        " Votorantim foi modificada para: " + contenido + " <br /> Usuário :" + idUsuario + "</td>  </tr> " +
                        " <hr style=" + (char)34 + "color:blue;" + (char)34 + "/>" +
                        " <tr> <td> Dear Sir: "+
                        " Your password to consult information the Supplier Portal was <br /> changed to: " + contenido + "<br /> " +
                        " Your ID: " + idUsuario + "</td></tr>" +
                        " <tr> " +
                        "    <td colspan=" + (char)34 + "2" + (char)34 + " class=" + (char)34 + "style1" + (char)34 + "> " +
                        "    <hr style=" + (char)34 + "color:blue;" + (char)34 + "/>" + 
                        "    </td> </tr> </table>";
            cuerpo += "</FONT></DIV></BODY></HTML>";
            
            //AlternateView plainView = AlternateView.CreateAlternateViewFromString(text,Encoding.UTF8, MediaTypeNames.Text.Plain);

           // LinkedResource img = new LinkedResource(@"C:\img\logo2.PNG", MediaTypeNames.Image.Jpeg);
            ContentType mimeType = new System.Net.Mime.ContentType("text/html");
            AlternateView alternate = AlternateView.CreateAlternateViewFromString(cuerpo, mimeType);

            //alternate.LinkedResources.Add(img);
            // Por último, vinculamos ambas vistas al mensaje...

            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            string correo = ConfigurationManager.AppSettings["correo"].ToString();
            msg.AlternateViews.Add(alternate);
            msg.To.Add(new MailAddress(destinatario));
            msg.From = new MailAddress(correo);
            msg.Subject = asunto;
            msg.IsBodyHtml =true;
            msg.AlternateViews.Add(alternate);//getCuerpoCorreo(contenido);

            string phrase = destinatario.ToUpper();
            string[] words;


            string ipCorreo = ConfigurationManager.AppSettings["ipCorreo"].ToString();

            words = phrase.Split((char)64);
            SmtpClient smtp = new SmtpClient();
            //if (words[1].Equals("MILPO.COM"))
            //{
            //    smtp.Host = "10.0.44.52"; //interno
            //}
            //else
            //{
            smtp.Host = ipCorreo; //externo e interno
            //}
            smtp.EnableSsl = false;

            smtp.Port = 25;
            smtp.Credentials = CredentialCache.DefaultNetworkCredentials;
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;


            try
            {
                smtp.Send(msg);

                result = "";
            }
            catch (Exception ex)
            {
                result = "Hubo errores al enviar el mensaje.";
            }
            return result;
        }
        private static string getCuerpoCorreo(String mensaje)
        {
            // Initialize StringWriter instance.
            StringWriter stringWriter = new StringWriter();

            // Put HtmlTextWriter in using block because it needs to call Dispose.
            using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
            {
                string classValue = "ClassName";
                // The important part:

                
                //writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);
                writer.RenderBeginTag(HtmlTextWriterTag.Hr); // Begin #1
                writer.RenderEndTag(); // End #1

                    writer.RenderBeginTag(HtmlTextWriterTag.Img);
                    writer.AddAttribute(HtmlTextWriterAttribute.Src, "logo2.PNG");
                    writer.RenderEndTag();

                    //writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);
                    writer.RenderBeginTag(HtmlTextWriterTag.Div); // Begin #1
                    writer.AddStyleAttribute(HtmlTextWriterStyle.FontSize,"15");
                    writer.AddStyleAttribute(HtmlTextWriterStyle.Color, "blue");
                    writer.Write("Estimado usuario para tener acceso a realizar sus consultas por internet tendrá que usar los siguientes datos:");
                    writer.RenderEndTag(); // End #1

                    writer.RenderBeginTag(HtmlTextWriterTag.Br);
                    writer.RenderEndTag();

                    //writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);
                    writer.RenderBeginTag(HtmlTextWriterTag.Div); // Begin #1
                    writer.AddStyleAttribute(HtmlTextWriterStyle.FontSize, "12");
                    writer.AddStyleAttribute(HtmlTextWriterStyle.Color, "blue");
                    writer.Write(mensaje);
                    writer.RenderEndTag(); // End #1

                //writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);
                writer.RenderBeginTag(HtmlTextWriterTag.Hr); // Begin #1
                writer.RenderEndTag(); // End #1

            }
            
            // Return the result.
            return stringWriter.ToString();
        }


        //public static string Configuracion(string destinatario, string asunto, string contenido)
        //{
        //    String result = "";


        //    String cuerpo = getCuerpoCorreo(contenido);
        //    try
        //    {
        //        //Configurando el cliente SMTP
        //        SmtpClient client = new SmtpClient();
        //        client.Host = "smtp.gmail.com";
        //        client.Port = 587;
        //        client.EnableSsl = true;
        //        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        //        client.UseDefaultCredentials = false;
        //        client.Credentials = new NetworkCredential("manueltn82@gmail.com", "");


        //        //Enviando correo
        //        System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
        //        mail.From = new MailAddress("rrojas@milpo.com");
        //        mail.To.Add(new MailAddress(destinatario));
        //        mail.Subject = asunto;
        //        mail.IsBodyHtml = true;
        //        mail.Body = cuerpo ;

        //        client.Send(mail);

        //        result = "";
        //    }
        //    catch (Exception ex)
        //    {
        //        result = "Hubo errores al enviar el mensaje.";
        //    }
        //    return result;
        //}

        public static string NuevaContrasena() {
            var chars = "0123456789";
            var random = new Random();
            var result = new string(
                Enumerable.Repeat(chars, 6)
                          .Select(s => s[random.Next(s.Length)])
                          .ToArray());

            return result.ToString();
        }

        public static string NuevaContrasenaIntra()
        {
            var chars = "0123456789";
            var charc = "abcdefghijklmnopqrstuvwxyz";
            var random = new Random();
            var result = new string(
                Enumerable.Repeat(chars, 7)
                          .Select(s => s[random.Next(s.Length)])
                          .ToArray());
            var resultc = new string(
                Enumerable.Repeat(charc, 1)
                          .Select(s => s[random.Next(s.Length)])
                          .ToArray());            
            return result.ToString() + resultc.ToString();
        }
    }
}